﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace OrderForm
{
    public partial class OrderForm : Form
    {
        Order.OrderService service;
        public OrderForm()
        {
            InitializeComponent();
            service = new Order.OrderService();
        }

        private void Create_Click(object sender, EventArgs e)
        {
            new CreateForm(service).ShowDialog(this);
        }

        private void Delete_Click(object sender, EventArgs e)
        {
            new DeleteForm(service).ShowDialog(this);
        }

        private void Modify_Click(object sender, EventArgs e)
        {
            new DeleteForm(service).ShowDialog(this);
            new CreateForm(service).ShowDialog(this);
        }

        private void OrderForm_Load(object sender, EventArgs e)
        {
            DataList.DataSource = service.Orders;
        }

        private void Inquiry_Click(object sender, EventArgs e)
        {
            new InquiryForm(service).ShowDialog(this);
        }

        private void Export_Click(object sender, EventArgs e)
        {
            Stream stream;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK && (stream = saveFileDialog1.OpenFile()) != null)
            {
                service.Export(stream);
                stream.Close();
            }
        }

        private void Import_Click(object sender, EventArgs e)
        {
            Stream stream;
            if (openFileDialog1.ShowDialog() == DialogResult.OK && (stream = openFileDialog1.OpenFile()) != null)
            {
                try
                {
                    var newSer = Order.OrderService.Import(stream);
                    foreach(var o in newSer.Orders)
                    {
                        if(!service.Orders.Contains(o)) service.Orders.Add(o);
                    }
                }
                catch(System.Runtime.Serialization.SerializationException x)
                {
                    Console.WriteLine(x);
                    MessageBox.Show(this, "非订单文件或订单文件已损坏。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                }
                finally
                {
                    stream.Close();
                }
            }
        }
    }
}
